import json

from django.db import connection

from app.service import ali_sms
from libs import time_helper, common
from libs.db import DB


def send_sms(subject_code, sms_typ, tel):
    ym = time_helper.ts_to_time_str(time_format='%y%m')
    biz_id = '{}-{}-{}'.format(ym, subject_code, sms_typ)
    with connection.cursor() as cursor:
        dh = DB('cs_sms_logs', conn=cursor)
        db_sms_log = dh.one(['id', 'is_send'], {'biz_id': biz_id})
        db_sms_log_id = db_sms_log.get('id', 0)
        db_sms_log_is_send = db_sms_log.get('is_send', 0)
        if db_sms_log_is_send == 0:
            sign_name = '信资商城盘点通知'
            template_code = 'SMS_232171657'
            resp_obj = ali_sms.send_sms(biz_id, tel, sign_name, template_code)
            is_send = 0
            resp_code = resp_obj.get('Code', '')
            resp = {'RequestId': resp_obj.get('RequestId'), 'Code': resp_code}
            resp_str = json.dumps(resp)
            if resp_code == 'OK':
                is_send = 1
            now = common.get_ts()
            if db_sms_log_id == 0:
                data = {
                    'biz_id': biz_id,
                    'tel': tel,
                    'typ': sms_typ,
                    'resp': resp_str,
                    'is_send': is_send,
                    'created': now,
                    'updated': now,
                }
                dh.insert(data)
            else:
                dh.update({'is_send': 1, 'updated': now}, {'id': db_sms_log_id})
        else:
            common.logger('短信已发送', 'warn')
